﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Facebook
{
    /// <summary>
    /// General helpers for the facebook API
    /// </summary>
    internal static class Helpers
    {
        /// <summary>
        /// method for converting a UNIX timestamp to a regular
        /// System.DateTime value (and also to the current local time)
        /// </summary>
        /// <param name="timestamp">value to be converted</param>
        /// <returns>converted DateTime in string format</returns>
        internal static DateTime ConvertUnixTimestampToDotNet(double unixTimeStamp)
        {
            // base date from unix EPOC
            DateTime baseUnixDate = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            //add the timestamp to the base unix date and return the local time
            return baseUnixDate.AddSeconds(unixTimeStamp).ToLocalTime();
        }


		///<summary>
		/// Converts a Dictionary to a JSON-formatted Associative Array.
		///</summary>
		///<param name="dict">Source Dictionary collection [string|string].</param>
		///<returns>JSON Associative Array string.</returns>
		internal static string ConvertToJSONAssociativeArray(Dictionary<string, string> dict)
		{
			var elements = new List<string>();

			foreach (var pair in dict)
			{
				if (!string.IsNullOrEmpty(pair.Value))
				{
					elements.Add(string.Format("\"{0}\":{2}{1}{2}", EscapeJSONString(pair.Key), EscapeJSONString(pair.Value), IsJSONArray(pair.Value) || IsBoolean(pair.Value) ? string.Empty : "\""));
				}
			}
			return "{" + string.Join(",", elements.ToArray()) + "}";
		}


		/// <summary>
		/// Converts a List collection of type string to a JSON Array.
		/// </summary>
		/// <param name="list">List of strings</param>
		/// <returns>string</returns>
		public static string ConvertToJSONArray(List<string> list)
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("[");
			foreach (var item in list)
			{
				builder.Append(string.Format("{0}{1}{0},", IsJSONArray(item) || IsBoolean(item) ? string.Empty : "\"", EscapeJSONString(item)));
			}
			builder.Replace(",", "]", builder.Length - 1, 1);
			return builder.ToString();
		}


		/// <summary>
		/// Escape backslashes and double quotes of valid JSON content string.
		/// </summary>
		/// <param name="originalString">string</param>
		/// <returns>string</returns>
		internal static string EscapeJSONString(string originalString)
		{
			return IsJSONArray(originalString) ? originalString : originalString.Replace("\\/", "/").Replace("/", "\\/").Replace("\\\"", "\"").Replace("\"", "\\\"").Replace("\r", "\\r").Replace("\n", "\\n");
		}


		/// <summary>
        /// Determines if input string is a formatted JSON Array.
        /// </summary>
        /// <param name="test">string</param>
        /// <returns>bool</returns>
        internal static bool IsJSONArray(string test)
        {
            return test.StartsWith("{") && !test.StartsWith("{*") || test.StartsWith("[");
        }


		/// <summary>
        /// Determines if input string is a boolean value.
        /// </summary>
        /// <param name="test">string</param>
        /// <returns>bool</returns>
        internal static bool IsBoolean(string test)
        {
            return test.Equals("false") || test.Equals("true");
        }
    }
}
